import { INestApplication } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { writeFileSync } from 'fs';
import { join } from 'path';

type Props = {
  /** 应用实例 */
  app: INestApplication<any>;
  /** 服务端口号 */
  port?: string | number;
};

export function createSwagger(props: Props) {
  const { app, port } = props;
  // const swaggerApiUrl = `http://localhost:${port}/api`;
  const swaggerJsonUrl = `http://localhost:${port}/swagger/json`;

  const config = new DocumentBuilder()
    .setTitle('Test example')
    .setDescription(
      `<a href=${swaggerJsonUrl} target="_blank">${swaggerJsonUrl}</a>`,
    )
    .setVersion('1.0')
    // .addTag('test')
    .build();
  const documentFactory = () => SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('swagger/api', app, documentFactory);
  SwaggerModule.setup('swagger', app, documentFactory, {
    jsonDocumentUrl: 'swagger/json',
  });
  // 保存OpenAPI规范文件
  writeFileSync(
    join(process.cwd(), 'swagger.json'),
    JSON.stringify(documentFactory(), null, 2),
  );
}
